
class Dashboard::AddressesController < Dashboard::BaseController

  before_action :require_logined, except: [:all_province]
  before_action :find_address, only: [:edit, :update, :destroy, :set_default_address]

  def index
    @addresses = current_user.addresses
    respond_to do |format|
       format.html
       format.json { render json: {status: 'ok', data: @addresses, default_id: current_user.default_address_id}}
     end
  end

  def new
    @address = current_user.addresses.new
  end

  def set_default_address
    @address.set_as_default = 1
    @address.save

    @addresses = current_user.reload.addresses

    render json: {
        status: 'ok',
        data: @addresses,
        default_id: current_user.default_address_id
    }

  end

  def create
    current_addresses = current_user.addresses
    @address = current_addresses.new(address_params)
    if current_addresses.count < 5 && @address.save
      @addresses = current_user.reload.addresses
      render json: {
          status: 'ok',
          data: @addresses,
          default_id: current_user.default_address_id
      }
    else
      render json: {
        status: 'error',
        data: '创建失败，请重试！'
      }
    end
  end

  def edit
    render action: :new
  end

  def update
    @address.attributes = address_params
    if @address.save
      @addresses = current_user.reload.addresses
      render json: {
        status: 'ok',
        data: render_to_string(file: 'addresses/index')
      }
    else
      render json: {
        status: 'error',
        data: render_to_string(file: 'addresses/new')
      }
    end
  end

  def destroy
    @address.destroy!
    @addresses = current_user.addresses
    respond_to do |format|
       format.html
       format.json { render json: {status: 'ok', data: @addresses, default_id: current_user.default_address_id}}
     end

  end

  def all_province
    render json: {
      status: 'ok',
      data: ChinaCity.list
    }
  end

  private

  def address_params
    params.require(:address).permit(:contact_name, :cellphone, :address, :street_id,
      :zipcode, :set_as_default)
  end

  def find_address
    @address = current_user.addresses.find(params[:id])
  end

end
